/*
Copyright (C) 2009-2010 Xanadu Development Team

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; version 2
of the License.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

#include "PartyMembers.h"
#include "Party.h"
#include "../../server/Player.h"
#include "../../tools/MySQLM.h"
#include "World.h"
string valstr(int id);

Party::Party(World* world, Player* player) :
leader(player->getID()),
members(new PartyMembers)
{
	mysqlpp::Connection::thread_start();
	mysqlpp::Connection* conn = MySQL::getInstance()->getPool()->grab();
	mysqlpp::Query query = conn->query();
	query << "insert into party(world, leader) values(" << valstr(world->getID()) << "," << valstr(player->getID()) << ")";
	id = (int)query.execute().insert_id();
	MySQL::getInstance()->getPool()->release(conn);
	mysqlpp::Connection::thread_end();
	members->addMember(player);
}

Party::Party(int id, int leader) :
members(new PartyMembers),
id(id),
leader(leader)
{
}

Party::~Party() {
	mysqlpp::Connection::thread_start();
	mysqlpp::Connection* conn = MySQL::getInstance()->getPool()->grab();
	mysqlpp::Query query = conn->query();
	query << "delete from party where id=" << id;
	query.execute();
	MySQL::getInstance()->getPool()->release(conn);
	mysqlpp::Connection::thread_end();
	struct RemoveParty {
		void operator()(Player* player){
			player->setParty(0);
		}
	}
	removeParty;
	members->run(&removeParty);
	delete members;
}

void Party::removeMember(int playerid) {
	members->deleteMember(playerid);
}